<?php defined('SYSPATH') OR die('No direct access allowed.');

class Login_Controller extends Controller {

	private $main_page = 'login';

	public function __construct()
	{
		parent::__construct();		
		$this->user_model = new User_Model;
	}
	
	public function index() {
		$this::_login();
	}
	
	public function _login() {
		$this->view->main->errors=array();
		$this->view = new View('home_content');	
		if($_POST) {
			$this->post = new Validation($_POST);
			$this->post = $this->post->add_rules('username','required');
			$this->post = $this->post->add_rules('password','required');			
			if($this->post->validate()) {//validasi username dan password
				$user = stripslashes($_POST["username"]);
				$pwd = stripslashes($_POST["password"]);
				$res = $this->user_model->check_user_and_password($user,$pwd); 				
				if($res->count() == 1) {//jika benar password username tersebut					
					$this->session->create();//start session 
					$this->session->set('username',$user);// set session,catet username
					$this->session->set('id',$res->current()->ID_user);//catet id
					url::redirect('dashboard');
				}else{//password salah
					$this->post->add_error('password','wrong_pass');					
					$this->view->errors=$this->post->errors('login_error');										
				}
			}else{//jika salah satu username atau password tidak diisi				
				$this->view->errors=$this->post->errors('login_error');				
			}
		}
		$this->view->render(TRUE);
	}
	
	public function logout() {		
		$this->session->destroy();//hapus session
		url::redirect('login');
	}
	
}

